﻿using Batman.Core;
using IdentityModel.Client;
using IdentityServer4;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System.Net.Http;
using System.Threading.Tasks;

namespace Batman.Web.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class TokenController : ControllerBase
    {
        IConfiguration Configuration;

        public TokenController(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        [HttpPost]
        public async Task<ResponseBase> Post([FromForm]AccountLoginInput account)
        {
            var cache = new DiscoveryCache(Configuration["ID4Server:Address"]);
            var disco = await cache.GetAsync();

            var client = new HttpClient();

            var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address = disco.TokenEndpoint,

                ClientId = Configuration["ID4Server:ClientId"],
                ClientSecret = Configuration["ID4Server:ClientSecret"],
                Scope = $"openid profile {IdentityServerConstants.LocalApi.ScopeName}",
                UserName = account.username,
                Password = account.password
            });
            if (tokenResponse.IsError)
            {
                return  new ResponseBase(false, tokenResponse.ErrorDescription);
            }

            client.SetBearerToken(tokenResponse.AccessToken);
            var userInfoResponse = await client.GetAsync(disco.UserInfoEndpoint);

            if (!userInfoResponse.IsSuccessStatusCode)
            {
                return  new ResponseBase(false, "获取用户信息错误");
            }

            return new ResponseBase
            {
                Result = new
                {
                    accessToken = tokenResponse.AccessToken,
                    tokenResponse.ExpiresIn,
                    tokenResponse.Scope,
                    tokenResponse.TokenType,
                    userInfo = await userInfoResponse.Content.ReadAsStringAsync()
                }
            };
        }

    }

    public class AccountLoginInput
    {
        public string username { get; set; }

        public string password { get; set; }
    }

}